{% extends "base.html" %}

{% block title %}多模态翻译{% endblock %}

{% block styles %}
<style>
.translate-header {
    background: linear-gradient(120deg, #2b5876 0%, #4e4376 100%);
    color: white;
    padding: 2.5rem 0;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.translate-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 0 1rem;
}

.translate-card {
    border: none;
    border-radius: 15px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    margin-bottom: 2rem;
}

.translate-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 25px rgba(0, 0, 0, 0.1);
}

.translate-tabs {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 0.5rem;
    margin-bottom: 1.5rem;
    background: #f8f9fa;
    border-radius: 12px;
    padding: 0.5rem;
}

.translate-tab {
    flex: 1;
    padding: 1rem;
    text-align: center;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    color: #6c757d;
    font-weight: 500;
}

.translate-tab.active {
    background: #4e4376;
    color: white;
}

.translate-tab:hover:not(.active) {
    background: rgba(78, 67, 118, 0.1);
}

.translate-tab i {
    margin-right: 0.5rem;
    font-size: 1.1rem;
}

.language-selector {
    display: flex;
    align-items: center;
    margin-bottom: 1.5rem;
    background: #f8f9fa;
    border-radius: 12px;
    padding: 1rem;
}

.language-selector select {
    flex: 1;
    border: 2px solid #e9ecef;
    padding: 0.75rem;
    border-radius: 8px;
    font-size: 1rem;
    background-color: white;
    margin: 0 0.5rem;
}

.language-selector i {
    font-size: 1.5rem;
    color: #4e4376;
    margin: 0 1rem;
}

.input-area, .output-area {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 1.5rem;
}

.input-area textarea {
    border: 2px solid #e9ecef;
    border-radius: 8px;
    padding: 1rem;
    min-height: 150px;
    font-size: 1rem;
    width: 100%;
    resize: vertical;
}

.image-upload {
    border: 2px dashed #e9ecef;
    border-radius: 12px;
    padding: 2rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.image-upload:hover {
    border-color: #4e4376;
    background: rgba(78, 67, 118, 0.05);
}

.image-preview {
    max-width: 100%;
    max-height: 300px;
    border-radius: 8px;
    margin-top: 1rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.translate-btn {
    width: 100%;
    padding: 1rem;
    font-size: 1.1rem;
    font-weight: 500;
    border-radius: 10px;
    background: linear-gradient(45deg, #2b5876, #4e4376);
    border: none;
    color: white;
    transition: all 0.3s ease;
}

.translate-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(43, 88, 118, 0.3);
}

.result-card {
    display: none;
    margin-top: 2rem;
}

.result-section {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 1rem;
}

.result-section h6 {
    color: #4e4376;
    margin-bottom: 1rem;
    font-weight: 600;
}

.result-text {
    background: white;
    border-radius: 8px;
    padding: 1rem;
    min-height: 60px;
    white-space: pre-wrap;
}

.result-section .btn {
    display: block;
    width: 100%;
    margin-top: 1rem;
    background: linear-gradient(45deg, #2b5876, #4e4376);
    border: none;
    transition: all 0.3s ease;
}

.result-section .btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(43, 88, 118, 0.3);
}

@media (max-width: 768px) {
    .language-selector {
        flex-direction: column;
    }
    
    .language-selector select {
        margin: 0.5rem 0;
    }
    
    .language-selector i {
        transform: rotate(90deg);
        margin: 0.5rem 0;
    }

    .translate-tabs {
        grid-template-columns: repeat(2, 1fr);
    }
}

.audio-upload {
    border: 2px dashed #e9ecef;
    border-radius: 12px;
    padding: 2rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.audio-upload:hover {
    border-color: #4e4376;
    background: rgba(78, 67, 118, 0.05);
}

.audio-upload.border-primary {
    border-color: #4e4376;
    background: rgba(78, 67, 118, 0.05);
}

#audioPreview .btn-close {
    padding: 0.5rem;
}

#audioPreview audio {
    border-radius: 8px;
    background: #f8f9fa;
}

.document-upload {
    border: 2px dashed #e9ecef;
    border-radius: 12px;
    padding: 2rem;
    text-align: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.document-upload:hover,
.document-upload.border-primary {
    border-color: #4e4376;
    background: rgba(78, 67, 118, 0.05);
}
</style>
{% endblock %}

{% block content %}
<div class="translate-header">
    <div class="translate-container">
        <h1 class="display-4 mb-2">多模态翻译</h1>
        <p class="lead mb-0">支持文本、文档、图片和语音的智能翻译</p>
    </div>
</div>

<div class="translate-container">
    <div class="translate-card">
        <div class="card-body">
            <!-- 翻译类型切换 -->
            <div class="translate-tabs">
                <div class="translate-tab active" onclick="switchType('text')">
                    <i class="bi bi-file-text"></i>文本翻译
                </div>
                <div class="translate-tab" onclick="switchType('document')">
                    <i class="bi bi-file-pdf"></i>文档翻译
                </div>
                <div class="translate-tab" onclick="switchType('image')">
                    <i class="bi bi-image"></i>图片翻译
                </div>
                <div class="translate-tab" onclick="switchType('audio')">
                    <i class="bi bi-mic"></i>语音翻译
                </div>
            </div>

            <form id="translateForm" onsubmit="performTranslate(event)">
                <input type="hidden" name="type" id="translateType" value="text">
                
                <!-- 语言选择 -->
                <div class="language-selector">
                    <select class="form-select" name="source_lang">
                        <option value="zh">中文</option>
                        <option value="en">英语</option>
                        <option value="ja">日语</option>
                        <option value="ko">韩语</option>
                        <option value="fr">法语</option>
                        <option value="de">德语</option>
                        <option value="es">西班牙语</option>
                        <option value="ru">俄语</option>
                    </select>
                    <i class="bi bi-arrow-right"></i>
                    <select class="form-select" name="target_lang">
                        <option value="en">英语</option>
                        <option value="zh">中文</option>
                        <option value="ja">日语</option>
                        <option value="ko">韩语</option>
                        <option value="fr">法语</option>
                        <option value="de">德语</option>
                        <option value="es">西班牙语</option>
                        <option value="ru">俄语</option>
                    </select>
                </div>
                
                <!-- 文本输入区域 -->
                <div id="textInput" class="input-area">
                    <textarea class="form-control" name="text" 
                              placeholder="请输入要翻译的文本..."></textarea>
                </div>
                
                <!-- 文档上传区域 -->
                <div id="documentInput" class="input-area" style="display: none;">
                    <div class="file-upload document-upload" onclick="document.getElementById('documentFile').click()">
                        <input type="file" id="documentFile" name="document" 
                               accept=".pdf,.doc,.docx,.txt" style="display: none;"
                               onchange="handleDocumentSelect(event)">
                        <i class="bi bi-file-earmark-text display-4 mb-3"></i>
                        <p class="mb-0">点击或拖拽文档到此处</p>
                        <small class="text-muted">支持 PDF、Word、TXT 格式（小于50MB）</small>
                    </div>
                    <div id="documentPreview" class="document-preview" style="display: none;">
                        <div class="d-flex align-items-center">
                            <i class="bi bi-file-earmark-text me-2"></i>
                            <span class="filename"></span>
                            <button type="button" class="btn-close ms-auto" onclick="clearDocument()"></button>
                        </div>
                    </div>
                </div>
                
                <!-- 图片上传区域 -->
                <div id="imageInput" class="input-area" style="display: none;">
                    <div class="image-upload" onclick="document.getElementById('imageFile').click()">
                        <input type="file" id="imageFile" name="image" 
                               accept="image/*" style="display: none;">
                        <i class="bi bi-image display-4 mb-3"></i>
                        <p class="mb-0">点击或拖拽图片到此处</p>
                    </div>
                    <img id="imagePreview" class="image-preview" style="display: none;">
                </div>
                
                <!-- 语音输入区域 -->
                <div id="audioInput" class="input-area" style="display: none;">
                    <div class="audio-upload" onclick="document.getElementById('audioFile').click()">
                        <input type="file" id="audioFile" name="audio" 
                               accept="audio/*" style="display: none;"
                               onchange="handleAudioSelect(event)">
                        <i class="bi bi-cloud-upload display-4 mb-3"></i>
                        <p class="mb-0">点击或拖拽音频文件到此处</p>
                        <small class="text-muted">支持 MP3、WAV、M4A 等格式</small>
                    </div>
                    <div id="audioPreview" class="mt-3" style="display: none;">
                        <div class="d-flex align-items-center p-2 bg-light rounded">
                            <i class="bi bi-file-music me-2"></i>
                            <span class="filename"></span>
                            <button type="button" class="btn-close ms-auto" onclick="clearAudio()"></button>
                        </div>
                        <audio controls class="w-100 mt-2"></audio>
                    </div>
                </div>
                
                <button type="submit" class="translate-btn">
                    <i class="bi bi-translate me-2"></i>开始翻译
                </button>
            </form>

            <!-- 翻译结果 -->
            <div id="resultCard" class="result-card">
                <div class="result-section">
                    <h6><i class="bi bi-file-text me-2"></i>原文</h6>
                    <div id="originalText" class="result-text"></div>
                </div>
                <div class="result-section">
                    <h6><i class="bi bi-translate me-2"></i>译文</h6>
                    <div id="translatedText" class="result-text"></div>
                    <!-- 添加文档下载区域 -->
                    <div id="documentDownload"></div>
                </div>
                <!-- 标注图片预览 -->
                <div id="annotatedImage" class="result-section" style="display: none;">
                    <h6><i class="bi bi-image me-2"></i>标注结果</h6>
                    <img class="img-fluid rounded" style="max-width: 100%;">
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 切换翻译类型
function switchType(type) {
    // 更新隐藏字段
    document.getElementById('translateType').value = type;
    
    // 更新标签状态
    document.querySelectorAll('.translate-tab').forEach(tab => {
        if (tab.textContent.includes(
            type === 'text' ? '文本' : 
            type === 'document' ? '文档' :
            type === 'image' ? '图片' : '语音'
        )) {
            tab.classList.add('active');
        } else {
            tab.classList.remove('active');
        }
    });
    
    // 显示/隐藏相应的输入区域
    document.getElementById('textInput').style.display = type === 'text' ? 'block' : 'none';
    document.getElementById('documentInput').style.display = type === 'document' ? 'block' : 'none';
    document.getElementById('imageInput').style.display = type === 'image' ? 'block' : 'none';
    document.getElementById('audioInput').style.display = type === 'audio' ? 'block' : 'none';
    
    // 重置表单和结果
    document.getElementById('translateForm').reset();
    document.getElementById('resultCard').style.display = 'none';
    document.getElementById('imagePreview').style.display = 'none';
    document.getElementById('documentPreview').style.display = 'none';
    document.getElementById('audioPreview').style.display = 'none';
}

// 文件预览处理
document.getElementById('documentFile')?.addEventListener('change', handleDocumentSelect);
document.getElementById('imageFile')?.addEventListener('change', handleImageSelect);

function handleDocumentSelect(e) {
    const file = e.target.files[0];
    if (file) {
        // 检查文件类型
        const ext = file.name.split('.').pop().toLowerCase();
        const supportedTypes = ['pdf', 'doc', 'docx', 'txt'];
        if (!supportedTypes.includes(ext)) {
            alert('不支持的文件格式，请选择 PDF、Word 或 TXT 文件');
            e.target.value = '';
            return;
        }

        const preview = document.getElementById('documentPreview');
        preview.querySelector('.filename').textContent = file.name;
        preview.style.display = 'block';
    }
}

function handleImageSelect(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('imagePreview');
            preview.src = e.target.result;
            preview.style.display = 'block';
        }
        reader.readAsDataURL(file);
    }
}

// 处理音频文件选择
function handleAudioSelect(event) {
    const file = event.target.files[0];
    if (file) {
        // 创建音频上下文
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        
        // 创建文件读取器
        const reader = new FileReader();
        reader.onload = async function(e) {
            // 解码音频数据
            const audioData = await audioContext.decodeAudioData(e.target.result);
            
            // 设置每个片段的最大长度（30秒）
            const segmentDuration = 30;
            const sampleRate = 16000;
            const segmentSamples = segmentDuration * sampleRate;
            const totalSegments = Math.ceil(audioData.duration / segmentDuration);
            
            // 存储所有音频片段
            window.audioSegments = [];
            
            // 处理每个片段
            for (let i = 0; i < totalSegments; i++) {
                // 创建缓冲区
                const startSample = i * segmentSamples;
                const endSample = Math.min((i + 1) * segmentSamples, audioData.length);
                const segmentLength = endSample - startSample;
                
                const buffer = audioContext.createBuffer(1, segmentLength, sampleRate);
                const channelData = buffer.getChannelData(0);
                const inputData = audioData.getChannelData(0);
                
                // 复制音频数据到缓冲区
                for (let j = 0; j < segmentLength; j++) {
                    channelData[j] = inputData[startSample + j];
                }
                
                // 将音频数据转换为 16 位 PCM
                const pcmData = new Int16Array(segmentLength);
                for (let j = 0; j < segmentLength; j++) {
                    const s = Math.max(-1, Math.min(1, channelData[j]));
                    pcmData[j] = s < 0 ? s * 0x8000 : s * 0x7FFF;
                }
                
                // 创建 Blob
                const pcmBlob = new Blob([pcmData.buffer], { type: 'audio/pcm' });
                window.audioSegments.push(pcmBlob);
            }
            
            // 更新预览
            const preview = document.getElementById('audioPreview');
            preview.querySelector('.filename').textContent = file.name;
            preview.querySelector('audio').src = URL.createObjectURL(file); // 原始文件用于预览
            preview.style.display = 'block';
        };
        reader.readAsArrayBuffer(file);
    }
}

// 清除音频
function clearAudio() {
    const audioFile = document.getElementById('audioFile');
    const preview = document.getElementById('audioPreview');
    audioFile.value = '';
    preview.style.display = 'none';
    preview.querySelector('audio').src = '';
}

// 添加拖放支持
const audioUpload = document.querySelector('.audio-upload');
if (audioUpload) {
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        audioUpload.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        audioUpload.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        audioUpload.addEventListener(eventName, unhighlight, false);
    });

    function highlight(e) {
        audioUpload.classList.add('border-primary');
    }

    function unhighlight(e) {
        audioUpload.classList.remove('border-primary');
    }

    audioUpload.addEventListener('drop', handleDrop, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const file = dt.files[0];
        
        if (file && file.type.startsWith('audio/')) {
            const input = document.getElementById('audioFile');
            input.files = dt.files;
            input.dispatchEvent(new Event('change'));
        }
    }
}

// 添加文档拖放支持
const documentUpload = document.querySelector('.document-upload');
if (documentUpload) {
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        documentUpload.addEventListener(eventName, preventDefaults, false);
    });

    ['dragenter', 'dragover'].forEach(eventName => {
        documentUpload.addEventListener(eventName, e => {
            documentUpload.classList.add('border-primary');
        }, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        documentUpload.addEventListener(eventName, e => {
            documentUpload.classList.remove('border-primary');
        }, false);
    });

    documentUpload.addEventListener('drop', e => {
        const dt = e.dataTransfer;
        const file = dt.files[0];
        
        if (file) {
            const ext = file.name.split('.').pop().toLowerCase();
            const supportedTypes = ['pdf', 'doc', 'docx', 'txt'];
            if (supportedTypes.includes(ext)) {
                const input = document.getElementById('documentFile');
                input.files = dt.files;
                input.dispatchEvent(new Event('change'));
            } else {
                alert('不支持的文件格式，请选择 PDF、Word 或 TXT 文件');
            }
        }
    }, false);
}

// 翻译请求处理
async function performTranslate(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const type = formData.get('type');
    
    // 如果是音频翻译，处理所有片段
    if (type === 'audio' && window.audioSegments?.length > 0) {
        const submitBtn = event.target.querySelector('button[type="submit"]');
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>翻译中...';
        
        try {
            let originalTexts = [];
            let translatedTexts = [];
            
            // 依次处理每个片段
            for (let i = 0; i < window.audioSegments.length; i++) {
                const segmentFormData = new FormData();
                segmentFormData.append('type', 'audio');
                segmentFormData.append('audio', window.audioSegments[i], 'audio.pcm');
                segmentFormData.append('source_lang', formData.get('source_lang'));
                segmentFormData.append('target_lang', formData.get('target_lang'));
                
                const response = await fetch('/translate/api/translate', {
                    method: 'POST',
                    body: segmentFormData
                });
                
                const data = await response.json();
                if (data.status === 'success') {
                    // 从返回结果中提取文本
                    if (data.result.result) {
                        if (data.result.result.source) originalTexts.push(data.result.result.source);
                        if (data.result.result.target) translatedTexts.push(data.result.result.target);
                    } else {
                        // 兼容旧格式
                        if (data.result.original) originalTexts.push(data.result.original);
                        if (data.result.translated) translatedTexts.push(data.result.translated);
                    }
                }
            }
            
            // 显示完整结果
            document.getElementById('originalText').textContent = originalTexts.join('\n');
            document.getElementById('translatedText').textContent = translatedTexts.join('\n');
            document.getElementById('resultCard').style.display = 'block';
            document.getElementById('resultCard').scrollIntoView({ behavior: 'smooth' });
            
        } catch (error) {
            console.error('翻译错误:', error);
            alert('翻译请求失败');
        } finally {
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="bi bi-translate me-2"></i>开始翻译';
        }
        return;
    }
    
    // 其他类型的翻译保持不变
    const resultCard = document.getElementById('resultCard');
    const submitBtn = event.target.querySelector('button[type="submit"]');
    
    try {
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>翻译中...';
        
        const response = await fetch('/translate/api/translate', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        if (data.status === 'success') {
            document.getElementById('originalText').textContent = data.result.original;
            document.getElementById('translatedText').textContent = data.result.translated;
            
            // 如果是文档翻译，添加下载链接
            if (type === 'document' && data.result.translated_url) {
                const downloadLink = document.createElement('a');
                // 显示一个可见的下载按钮
                downloadLink.href = data.result.translated_url;
                downloadLink.className = 'btn btn-primary mt-3';
                downloadLink.innerHTML = '<i class="bi bi-download me-2"></i>下载翻译后的文档';
                downloadLink.download = data.result.translated;
                downloadLink.target = '_blank';  // 在新标签页打开
                
                const downloadArea = document.getElementById('documentDownload');
                const existingLink = downloadArea.querySelector('.btn');
                if (existingLink) {
                    existingLink.remove();
                }
                downloadArea.appendChild(downloadLink);
            }
            
            // 显示标注图片（如果有）
            const annotatedImage = document.getElementById('annotatedImage');
            if (data.result.annotated_image) {
                annotatedImage.querySelector('img').src = '/static/uploads/' + data.result.annotated_image;
                annotatedImage.style.display = 'block';
            } else {
                annotatedImage.style.display = 'none';
            }
            
            resultCard.style.display = 'block';
            resultCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } else {
            alert(data.message || '翻译失败');
        }
    } catch (error) {
        console.error('翻译错误:', error);
        alert('翻译请求失败');
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="bi bi-translate me-2"></i>开始翻译';
    }
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    switchType('text');
});
</script>
{% endblock %} 